package com.cat.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cat.yygh.cmn.client.DictFeignClient;
import com.cat.yygh.common.exception.YyghException;
import com.cat.yygh.enums.DictEnum;
import com.cat.yygh.hosp.mapper.HospitalSetMapper;
import com.cat.yygh.hosp.repository.HospitalRepository;
import com.cat.yygh.hosp.service.HospitalService;
import com.cat.yygh.model.hosp.Hospital;
import com.cat.yygh.model.hosp.HospitalSet;
import com.cat.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service

public class HospitalServiceImpl implements HospitalService {
    @Autowired
    /*注入持久层*/
    private HospitalRepository hospitalRepository;
    @Autowired
    /*注入平台的持久层*/
    private HospitalSetMapper hospitalSetMapper;
    /*注入服务调用的类*/
    @Autowired
    private DictFeignClient dictFeignClient;

    /*上传医院信息服务层*/
    @Override
    public void saveHospital(Map<String, Object> resultMap) {
        /*将map转换成字符串*/
        String s = JSONObject.toJSONString(resultMap);
        /*将字符串转换成指定的对象*/
        Hospital hospital = JSONObject.parseObject(s, Hospital.class);

        String hoscode = hospital.getHoscode();
        Hospital hospitalData = hospitalRepository.findByHoscode(hoscode);
        if (hospitalData == null){
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
        }else {
            hospital.setId(hospitalData.getId());

            hospital.setStatus(hospitalData.getStatus());
            hospital.setCreateTime(hospitalData.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(hospitalData.getIsDeleted());}
        hospitalRepository.save(hospital);
    }

    /*查询平台存的SignKey*/
    @Override
    public String getSignKeyWithHoscode(String hosCode) {
        /*新建一个查询构造器*/
        QueryWrapper<HospitalSet> hospitalSetQueryWrapper = new QueryWrapper<HospitalSet>();
        hospitalSetQueryWrapper.eq("hoscode",hosCode);
        /*将查询条件放进去查询*/
        HospitalSet hospitalSet = hospitalSetMapper.selectOne(hospitalSetQueryWrapper);
        if (hospitalSet == null){
            throw new YyghException(20001,"该医院信息不存在");
        }
        return hospitalSet.getSignKey();
    }

    @Override
    public Hospital getHoospitalByHoscode(String hoscode) {
        return hospitalRepository.findByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> getPageList(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matching = ExampleMatcher.matching()//构造对象
                //.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式 模糊查询
                .withMatcher("hosname",ExampleMatcher.GenericPropertyMatchers.contains())
                .withIgnoreCase(true);//忽略大小写
        Example<Hospital> hospitalExample = Example.of(hospital,matching);
        /*船舰分页对象*/
        PageRequest pageRequest = PageRequest.of(page-1, limit, Sort.by("createTime").ascending());
        Page<Hospital> result = hospitalRepository.findAll(hospitalExample, pageRequest);
        result.getContent().stream().forEach(item->{
            this.packHospital(item);
        });
        return result;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override
    public Hospital getHospById(String id) {
        Hospital hospital = hospitalRepository.findById(id).get();
        this.packHospital(hospital);
        return hospital;
    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        /*定义一个map*/
        Map<String,Object> map = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(this.getHoospitalByHoscode(hoscode));
        map.put("hospital",hospital);
        //预约规则
        map.put("bookingRule",hospital.getBookingRule());
        hospital.setBookingRule(null);
        return map;
    }

    /**
     * 封装数据
     *
     */
    private Hospital packHospital(Hospital hospital) {
        String hostype = hospital.getHostype();
        String provinceCode = hospital.getProvinceCode();
        String cityCode = hospital.getCityCode();
        String districtCode = hospital.getDistrictCode();
        String province = dictFeignClient.getNameByValue(Long.parseLong(provinceCode));
        String city = dictFeignClient.getNameByValue(Long.parseLong(cityCode));
        String district = dictFeignClient.getNameByValue(Long.parseLong(districtCode));
        String level = dictFeignClient.getNameByDictCodeAndValue(DictEnum.HOSTYPE.getDictCode(), Long.parseLong(hostype));

        hospital.getParam().put("level",level);
        hospital.getParam().put("address",province+city+district+hospital.getAddress());
        return hospital;
    }
}
